package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.CategoryDao;
import com.itheima.global.BusinessException;
import com.itheima.po.Category;
import com.itheima.po.Code;
import com.itheima.po.Dish;
import com.itheima.po.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void deleteByIdOnNoUse(Long id) {
//        2、判断菜品数据库中是否已经存在
//        3、如果不存在，给前端响应一个失败的提示，查询没有此菜品
//        4、如果存在则判断需要删除的菜品是否在其他菜品或者套餐中占用
//        5、如果占用则不能删除
//        6、如果没有占用就在数据库中删除数据，并将响应结果返回给前端

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        通过查询id数量比较，查询菜品表中的id是否被使用
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count = (int) dishService.count(dishLambdaQueryWrapper);
        if(count > 0){
            throw new BusinessException(Code.DELETE_ERROR,"该分类被菜品使用，无法删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        通过查询id数量比较，查询菜品表中的id是否被使用
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        count = (int) setmealService.count(setmealLambdaQueryWrapper);
        if(count > 0){
            throw new BusinessException(Code.DELETE_ERROR,"该套餐被套餐使用，无法删除");
        }
        this.removeById(id);

    }
}
